package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;


    @Override
    @Async   //标明当前方法是一个异步方法
    public void autoScanWmNews(Long newsId) throws Exception {
        //0入参判空
        if (newsId == null) {
            log.warn("newsId为空");
            return;
        }

        //1 查询新闻信息
        //1.1 新闻为空 响应失败
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }

        //2 提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);
        //3 提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> image = getImage(images, content);

        //两个技术栈 DFA算法 和 OCR技术！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
        //3.2 通过OCR提取图片中的文字
        String textFromOcr = ocrCheck(image);
        text = text + "_" + textFromOcr;

        //3.5 使用DFA算法进行自建敏感词处理
        Boolean dfaResult = dfaCheck(text);
        if (!dfaResult) {
            //DFA 检测不通过的话 需要更新一下啊文章状态
            updateNews(newsId.intValue(), 2, "DFA审核没有通过", null);
            return;
        }


        //4 调用文字审核接口
        //4.1审核失败 - - wmNews修改方法
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean suggestion = getSuggestion(textScan, null, newsId.intValue());
        if (!suggestion) {
            log.warn("文字审核失败");
            return;
        }

        //5 调用图片审核接口
        //5.1审核失败 - - wmNews修改方法

        Map imageScan = greenImageScan.imageScan(image);
        Boolean suggestion2 = getSuggestion(imageScan, null, newsId.intValue());
        if (!suggestion2) {
            log.warn("图片审核失败");
            return;
        }
        //6 远程调用ArticleClient保存文章
        //6.1 判断响应结果是不是200
        ArticleDto dto = wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        Integer code = responseResult.getCode();
        if (code != 200) {
            log.warn("文章保存失败");
            return;
        }
        long articleId = (long) responseResult.getData();
        //7 将articleId回写的到wmNews表中
        updateNews(newsId.intValue(), 9, "审核通过", articleId);

    }

    /**
     * 接收图片 提取图片里面的文字 并返回
     *
     * @param images
     * @return
     * @throws IOException
     * @throws TesseractException
     */
    private String ocrCheck(List<byte[]> images) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(images)) {
            return "";
        }

        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            //调用ocr工具 提取里面的照片
            ByteArrayInputStream stream = new ByteArrayInputStream(image);
            BufferedImage read = ImageIO.read(stream);

            String text = OcrUtil.doOcr(read);

            //将文字内容组合成一共字符串 最终返回
            builder.append("_").append(text);
        }

        return builder.toString();
    }


    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自建敏感词库
     *
     * @param text
     * @return
     */
    private Boolean dfaCheck(String text) {
        if (StringUtils.isBlank(text)) {
            return true;
        }
        //0.1 调用敏感词 mapper 查询所有敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(wmSensitives)) {
            return true;
        }
        List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(words)) {
            return true;
        }


        //0.2 DFA初始化
        SensitiveWordUtil.initMap(words);

        //0.3 DFA敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);

        //0.4
        return CollectionUtils.isEmpty(result);
    }


    /**
     * 提取文字
     *
     * @param title   标题
     * @param content 内容
     * @return String
     */
    private String getText(String title, String content) {
        if (StringUtils.isBlank(content)) {
            return title;
        }
        // 提取content里面的文字内容
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            return title;
        }
        StringBuilder builder = new StringBuilder();
        for (Map map : maps) {
            if (CollectionUtils.isEmpty(map)) {
                continue;
            }

            Object type = map.get("type");
            if ("text".equals(type)) {
                String value = (String) map.get("value");
                builder.append(value);
            }

        }
        //2 将content文字和内容和title进行组合
        builder.append("_").append(title);
        //3 返沪组合后的结果
        return builder.toString();
    }

    /**
     * 提取图片
     *
     * @param images  封面图
     * @param content 内容
     * @return List
     */
    private List<byte[]> getImage(String images, String content) {
        List<String> allImageList = new ArrayList<>();

        // 1. 判断images是否为空
        if (StringUtils.isNotBlank(images)) {
            // 2. 提取images里面的图片链接（,) split()
            String[] split = images.split(",");
            if (ArrayUtils.isNotEmpty(split)) {
                List<String> list = Arrays.asList(split);

                //加入到大的集合中
                allImageList.addAll(list);
            }

        }

        // 3. 提取content里面的图片
        if (StringUtils.isNotBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map map : maps) {
                    if (CollectionUtils.isEmpty(map)) {
                        continue;
                    }
                    Object type = map.get("type");
                    if ("image".equals(type)) {
                        String value = (String) map.get("value");
                        allImageList.add(value);

                    }
                }

            }
        }

        // 4. 把上面两组图片地址 合并在一起
        List<byte[]> result = new ArrayList<>();
        for (String url : allImageList) {
            if (StringUtils.isEmpty(url)) {
                continue;
            }

            // 5. 借助minIO的download将string转为byte[]
            byte[] bytes = minIoTemplate.downLoadFile(url);
            result.add(bytes);
        }

        // 6. 组装byte[]集合，并返回
        return result;
    }


    /**
     * 分析阿里云审核结果
     *
     * @param result result
     * @param newsId newsId
     * @return Boolean
     */

    private Boolean getSuggestion(Map result, Long articleId, Integer newsId) {
        if (!CollectionUtils.isEmpty(result)) {
            Object suggestion = result.get("suggestion");
            if ("pass".equals(suggestion)) {
                return true;
            } else if ("block".equals(suggestion)) {
                updateNews(newsId, 2, "不通过", null);
                return false;

            } else if ("review".equals(suggestion)) {
                // 不确定
                updateNews(newsId, 3, "不确定", null);
                return false;
            }
        }
        return true;
    }

    /**
     * 回写news状态
     *
     * @param newsId    新闻id
     * @param status    状态
     * @param reason    审核结果
     * @param articleId 文章id
     * @return Boolean
     */

    private Boolean updateNews(Integer newsId, Integer status, String reason, Long articleId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setReason(reason);
        wmNews.setStatus(status.shortValue());
        wmNews.setArticleId(articleId);

        int updateResult = wmNewsMapper.updateById(wmNews);

        return updateResult == 1;
    }

    /**
     * ArticleDto入参转换
     *
     * @param wmNews wmNews
     * @return ArticleDto
     */
    public ArticleDto wmNews2ArticleDto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);

        //处理差异字段
        Integer channelId = wmNews.getChannelId();
        WmChannel wmChannel = wmChannelMapper.selectById(channelId);
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }


        Integer userId = wmNews.getUserId();
        dto.setAuthorId(userId.longValue());
        WmUser wmUser = wmUserMapper.selectById(userId);
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        //布局方式
        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());

        return dto;
    }

    @Autowired
    private IScheduleClient scheduleClient;

    /**
     * 消费延迟队列数据
     */
    //todo 消费延迟队列数据
    @Override
    @Scheduled(fixedRate = 1000)
    public void getTask() {
        System.out.println("获取任务执行中=====");
        ResponseResult responseResult = scheduleClient.poll();
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("没有可消费的任务");
            return;
        }
        String data = JSON.toJSONString(responseResult.getData());
        if (StringUtils.isEmpty(data)) {
            log.warn("没有可消费的任务");
            return;
        }

        Task task = JSON.parseObject(data, Task.class);
        if (task == null) {
            log.warn("没有可消费的任务");
            return;
        }

        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        if (wmNews == null) {
            log.warn("参数缺失");
            return;
        }

        try {
            autoScanWmNews(wmNews.getId().longValue());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
